from web_ import constants, db
from web_.models import User, News, Comment, CommentLike
from web_.utils.response_code import RET
from . import news_blue
from flask import render_template, session, current_app, request, jsonify, g, abort
from web_.utils.common import user_login_data


@news_blue.route('/comment_like',methods=['POST'])
@user_login_data
def comment_like():
    '''
    评论点赞
    :return:
    '''
    # 接收参数
    user = g.user
    print("进来了")
    if not user:
        print("进来了")
        return jsonify(errno=RET.SESSIONERR, errmsg="参数错误")
    requests = request.json
    comment_id = requests.get('comment_id')
    news_id = requests.get('news_id')
    action = requests.get('action')
    # 判断参数
    if not all([comment_id, action]):
        return jsonify(errno=RET.NODATA, errmsg="参数不足")
    if action not in ['add','remove']:
        return jsonify(errno=RET.SESSIONERR, errmsg="参数错误")
    # 判断参数类型是否准确
    try:
        comment_id = int(comment_id)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.SESSIONERR, errmsg="类型作物")
    # 判断评论是否存在
    comment = None
    try:
        comment = Comment.query.get(comment_id)
    except Exception as f:
        current_app.logger.error(f)
    if not comment:
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    # 判断是点赞还是取消点赞
    if action=='add':
        comment_like = CommentLike()
        comment_like.comment_id = comment_id
        comment_like.user_id = user.id
        try:
            db.session.add(comment_like)
            db.session.commit()
            comment.like_count += 1
        except Exception as f:
            current_app.logger.error(f)
            db.session.rollback()
    else:
        comment_like = Comment.query.filter(CommentLike.user_id == user.id, CommentLike.comment_id == comment_id).first()

        if comment_like:
            db.session.delete(comment_like)
            comment.like_count -= 1
    return jsonify(errno=RET.OK, errmsg="操作成功乐乐")


@news_blue.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    '''
    新闻收藏【POST】
    :return:
    '''
    # 如果用户没有登录不用收藏
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="参数错误")
    request_collect = request.json
    news_id = request_collect['news_id']
    action = request_collect['action']
    # 判断是否传入值
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 如果ACTION 不等于 收藏/不收藏则返回
    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        news_id = int(news_id)
    except Exception as f:
        current_app.logger.error(f)
    # 查找新闻数据
    try:
        news = News.query.get(news_id)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if not news:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 如果新闻没有被收藏，就添加到收藏表
    if action == 'cancel_collect':
        if news not in user.collection_news:
            user.collection_news.remove(news)
    else:
        if news not in user.collection_news:
            user.collection_news.append(news)

    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blue.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    '''
    新闻评论
    1，判断用户是否登录
    2.
    :return:
    '''
    # 判断用户是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="未登录")
    # 接收参数 json
    request_msg = request.json
    # 新闻ID/评论内容/父ID --->如果是子内容
    news_id = request_msg.get('news_id')
    comment_s = request_msg.get('comment')
    parent_id = request_msg.get('parent_id')

    # 判断参数是否存在
    if not all([news_id, comment_s]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 根据新闻ID查找新闻
    try:
        news = News.query.get(news_id)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.DBERR, errmsg="未登录")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未登录")
    # 添加评论到
    # 初始化数据模型
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_s
    # 如果右父ID 则是子查询
    if parent_id:
        comment.parent_id = parent_id
    # 将评论添加到数据库
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as f:
        current_app.logger.error(f)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="添加数据库失败")
    # 返回相应
    return jsonify(errno=RET.OK, errmsg="评论成功", data=comment.to_dict())


@news_blue.route('/<int:new_id>')  # , methods=['POST']
@user_login_data
def news_detail(new_id):
    '''
    新闻详情页
    1.登录状态
    2.右边的排行榜
    3.新闻页面的展示
    4.评论的返回
    5 点赞的取消/显示
    6,当前用户是否关注过次新闻
    :param new_id:
    :return:
    '''
    # 右边排行榜
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as f:
        current_app.logger.error(f)
    news_dict_li = []
    for new in news_list:
        news_dict_li.append(new.to_dict())
    # 新闻数据的显示
    try:
        news = News.query.get(new_id)
    except Exception as f:
        current_app.logger.error(f)
        abort(404)
    if not news:
        abort(404)
    news.clicks += 1

    '''评论列表的展示：
    1. 在MYSQL中查找是否右评论列表的数据
    返回给界面
    '''
    comments = []
    try:
        comments = Comment.query.filter(Comment.news_id==new_id).order_by(Comment.create_time.desc()).all()
    except Exception as f:
        current_app.logger.error(f)
    comment = []
    for comment_msg in comments:
        comment.append(comment_msg.to_dict())
    #
    # 点赞/取消点赞
    # 1. 根据新闻new_id查找当前页面下的所有评论comments ID
    # 2  CommentLike()根据评论ID 和用户 ID 查找当前新闻页面的所有点赞ID

    comment_like_ids = []
    if g.user:
        try:
            comment_ids = [comment_s.id for comment_s in comments]
            comment_like_model = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),CommentLike.user_id==g.user.id).all()
            comment_like_ids = [k.comment_id for k in comment_like_model]  # 所有的点赞ID
        except Exception as f:
            current_app.logger.error(f)
            # return jsonify(errno=RET.DBERR, errmsg="查询错误")
    # 判断当前页面都有那条评论被点赞
    comment_list = []
    for item in comments if comments else []:
        comment_dict = item.to_dict()
        comment_dict['is_like'] = False
        # 判断用户是否点赞该评论
        if g.user and item.id in comment_like_ids:
            comment_dict["is_like"] = True
        comment_list.append(comment_dict)
    User
        # 当前登录用户是否关注当前新闻作者
    is_followed = False
    # 判断用户是否收藏过该新闻
    is_collected = False
    if g.user:
        if news in g.user.collection_news:
            is_collected = True
        if news.user.followers.filter(User.id == g.user.id).count() > 0:
            is_followed = True

    # 下方为返回给前端的数据
    data = {
        "user": g.user.to_dict() if g.user else None,
        'news': news.to_dict() if news else None,
        'news_dict_list': news_dict_li,
        'comments': comment,
        'is_collected':is_collected,
        "comments": comment_list,
        "is_followed": is_followed
    }
    return render_template('news/detail.html', data=data)


@news_blue.route('/followed_user', methods=["POST"])
@user_login_data
def followed_user():
    """关注/取消关注用户"""

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询到关注的用户信息
    try:
        author = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库失败")

    if not author:
        return jsonify(errno=RET.NODATA, errmsg="未查询到用户数据")

    # 根据不同操作做不同逻辑
    if action == "follow":
        if author not in user.followed:
            user.followed.append(author)
    else:
        if author in user.followed:
            user.followed.remove(author)

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")

    return jsonify(errno=RET.OK, errmsg="操作成功")
